<template>
    <div class="container text-center">
        <div class="row mb-3">
            <div class="col">
                <div class="input-group">
                    <input type="text" class="form-control" list="pidDatalistOptions" placeholder="topicId" v-model="pid" aria-label="topicId"
                        aria-describedby="button-query-attachment">
                    <button type="button" class="btn btn-outline-secondary" @click="queryTopic" id="button-query-attachment"
                        :disabled="pid === null || state.query">查找资源</button>
                    <datalist id="pidDatalistOptions">
                      <option :value="item" v-for="item in pids" :key="item"/>
                    </datalist>
                </div>
            </div>
            <div class="col-4">
                <div class="input-group">
                    <button type="button" class="btn btn-outline-secondary" @click="openImageWithNewTab(topicLocal?.attachments)"
                        :disabled="topicLocal.attachments && topicLocal.attachments.length <= 0">所有图片</button>
                </div>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col">
                <ol class="list-group">
                    <li class="list-group-item list-group-item-action overflow-hidden">
                        <div class="d-flex w-100 justify-content-between">
                            <h5 class="mb-1">{{topicLocal.topicId}}</h5>
                        </div>
                        <p class="text-start">{{topicLocal.title}}</p>
                        <div class="text-start" ref="contentDom"></div>
                        <div class="d-flex w-100 justify-content-between">
                            <small>{{topicLocal.user?.nickname}}</small>
                            <small>{{topicLocal.createTime}}</small>
                        </div>
                    </li>
                </ol>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <ol class="list-group">
                    <li class="list-group-item list-group-item-action overflow-hidden" v-for="item in topicLocal.attachments"
                        :key="item.id">
                        <div class="d-flex w-100 justify-content-between">
                            <h5 class="mb-1">{{item.id}}</h5>
                            <small>{{item.category}}</small>
                        </div>
                        <small class="text-break">{{item.remoteUrl}}</small>
                        <div class="d-flex w-100 justify-content-between">
                            <button @click="openImageWithNewTab([item])" v-if="item.category === 'images'"><i
                                    class="bi bi-box-arrow-right"></i></button>
                        </div>
                    </li>
                </ol>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { sendMessage, localSave, localStorage } from "@/utils/api"
    import { Reactive } from "@vue/reactivity";
    import type {ComponentInternalInstance} from "vue"
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const pid : Ref<string> = ref("")
    const pids: Reactive<string[]> = reactive([])
    const topicLocal: Reactive<any> = reactive({})
    const contentDom : Ref<InstanceType<typeof HTMLDivElement> | null>= ref(null)
    const state = reactive({
        query: false
    })

    const props = defineProps({
        url: {
            type: String,
            default: '',
        },
    })
    onMounted(async () => {
        const tab = await getCurrentTab()
        console.log(tab.url)
        
        const localObj = await localStorage().get("topic")
        if (localObj['topic']?.topicIds) {
            pids.splice(0, pids.length, ...localObj['topic'].topicIds)
        }
        if (tab.url) {
            const tabPid = new URL(tab.url).searchParams.get('pid') as string
            if (!tabPid) {
                tabPid = pids[0]
            }
            pid.value = tabPid
            return
        }
    })
    
    watch(pid, async (newValue, _) => {
        // if (newValue?.length <= 0) return
        const localObj = await localStorage().get("topic")
        // console.log("newValue:", newValue)
        if (!localObj['topic'] || !localObj['topic'].topicIds.includes(newValue)) {
            // 获取当前pid对应的数据
            return
        }
        // 当前pid移动到首位
        pids.splice(pids.indexOf(newValue), 1)
        pids.unshift(newValue)
        localObj['topic'].topicIds.splice(0, localObj['topic'].topicIds.length, ...pids)
        await localSave('topic', localObj['topic'])
        // 读取当前topic
        Object.assign(topicLocal, localObj['topic'].topic[newValue])
        if (contentDom.value) {
            contentDom.value.innerText = ''
            contentDom.value.appendChild(new DOMParser().parseFromString(topicLocal.content, 'text/html').body.firstElementChild as Node)
        }
    })
    const queryTopic = async () => {
        try {
            state.query = true
            const {topic, error} = await sendMessage({ action: 'topic', topicId: pid.value })
            console.log(topic, error)
            if (!topic) {
                proxy?.$toast(`topic: ${error}`)
                return
            }
            // 保存pid和topic到topic
            const localObj = await localStorage().get("topic")
            // 初始化
            if (!localObj['topic']) {
                localObj['topic'] = {topicIds: [], attachments: {}, topic: {}}
            }
            if (Object.keys(localObj['topic'].topic).length <= 0) {
                localObj['topic'].topic = {}
            }
            // 当前pid缓存到首位
            if (pids.includes(pid.value)) {
                pids.splice(pids.indexOf(pid.value), 1)
            }
            pids.unshift(pid.value)
            localObj['topic'].topicIds.splice(0, localObj['topic'].topicIds.length, ...pids)
            localObj['topic'].topic[pid.value] = topic
            await localSave('topic', localObj['topic'])
            // 读取当前topic
            Object.assign(topicLocal, topic)
            if (contentDom.value) {
                contentDom.value.innerText = ''
                contentDom.value.appendChild(new DOMParser().parseFromString(topicLocal.content, 'text/html').body.firstElementChild as Node)
            }
        } finally {
            state.query = false
        }
    }
    const openImageWithNewTab = async (items : any[]) => {
        items = items.filter(item => item.category === 'images')
        if (items.length <= 0) return
        await sendMessage({ action: 'openTabWithImages', items: items });
    }
</script>

<style scoped>
.container {
    min-height: 80vh;
}
</style>